//
//  HDRecognizeeEditVC.swift
//  HuaDaoPeifu
//
//  Created by 刘杰 on 2018/7/13.
//  Copyright © 2018年 paiyipai. All rights reserved.
//
enum HDRecognizeeEditVCMode {
    case Add,Modify
}

import UIKit
// import HXPhotoPicker
import SVProgressHUD

/*
 新增：
 1. 判断是否有被保人中有“本人” existinfo
    1）如果有，关系栏中就不能选“本人”
    2）如果没有，则可以选“本人”
        1）再获取本人基本信息 orzinfo,
            * 选“本人”默认填写基本信息
            * “子女”清除基本默认信息
 修改：
 1. 判断被保人中有没有本人 existinfo
    1）有：判断当前是不是本人 selfinfo
        * 是：关系可以修改成“子女”或“本人”
        * 不是：关系不能选“本人”
    2）没有：关系可选为“子女”或“本人”
 */
class HDRecognizeeEditVC: UITableViewController{
    
    var editRecognizee : HDRecognizeeModel?{
        didSet{
            if let model = editRecognizee {
                model.info_id = model.id
            }
        }
    }
    
    fileprivate var detail = HDRecognizeeDetailModel()
    fileprivate var recognizee = HDRecognizeeModel()
    fileprivate var numberOfSections = 4
    
    @IBOutlet weak var nameTF: UITextField!
    @IBOutlet weak var genderLB: UILabel!
    @IBOutlet weak var relationLB: UILabel!
    @IBOutlet weak var phoneTF: UITextField!
    @IBOutlet weak var addressTF: UITextField!
    @IBOutlet weak var emailTF: UITextField!
    @IBOutlet weak var accountNameTF: UITextField!
    @IBOutlet weak var accountNumTF: UITextField!
    @IBOutlet weak var accountNumTF2: UITextField!
    @IBOutlet weak var bankNameTF: UITextField!
    @IBOutlet weak var subBankName: UITextField!
    @IBOutlet weak var identifierTypeLB: UILabel!
    @IBOutlet weak var addressBtn: UIButton!
    @IBOutlet weak var identifierNumTF: UITextField!
    
    @IBOutlet weak var identifierCell: HDRecognizeeIdentifierUploadCell!
    @IBOutlet weak var multiUploadCell: HDRecognizeeMultiImageUploadCell!
    
    var mode = HDRecognizeeEditVCMode.Add
    var orzinfo : HDOrzinfoModel?
    
    var genderPicker : SinglePickerView!
    var relationPicker : SinglePickerView!
    var typePicker : SinglePickerView!
    var addressPicker = AddressView.init(AddressListType.twoLine)
    
    var progressAlert = HDProgressAlert()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        initMode()
    }
    
    func setupUI() {
        // 为多图选择器的cell设置刷新height的block
        let indexPath1 = IndexPath(row: 1, section: 4)
        multiUploadCell.photoViewChangeHeightBlock = {[unowned self](cell) in
            //self.tableView.reloadRows(at: [indexPath1], with: .bottom)
            self.tableView.reloadData()
        }
        let indexPath2 = IndexPath(row: 2, section: 3)
        identifierCell.photoViewChangeHeightBlock = {[unowned self](cell) in
            // self.tableView.reloadRows(at: [indexPath2], with: .bottom)
            self.tableView.reloadData()
        }
        
        genderPicker = SinglePickerView()
        genderPicker.delegate = self
        genderPicker.arr = ["男","女"] // 男 1   女 2
        
        relationPicker = SinglePickerView()
        relationPicker.delegate = self
        relationPicker.arr = ["本人","子女"] // 本人 0    子女 2
        
        typePicker = SinglePickerView()
        typePicker?.type = SingleListType.ID
        typePicker?.delegate = self
        
        addressPicker?.delegate = self
    }
    
    /// 根据业务流程，初始化页面状态
    func initMode() {
        // 如果是新增页面，则根据新增页面的规则，初始化页面数据
        
        recognizee.partone = detail
        if mode == .Add {
            // 判断被保人是否存在本人
            HDApiManagerHandler.existRecognizeeSelf {[unowned self] (result:HDApiResult?) in
                guard let result = result else {
                    return // 查询错误 atk不存在
                }
                
                if result.status == .Success {
                    self.relationPicker.arr = ["子女"]
                }else{
                    self.relationPicker.arr = ["本人","子女"]
                    HDApiManagerHandler.requestOrzinfo({ (orzinfo:HDOrzinfoModel?) in
                        if let orzinfo = orzinfo {
                            self.orzinfo = orzinfo
                            self.setDefaultOrzinfo(orzinfo)
                        }else {
                            
                        }
                    })
                }
            }
        }// 否则按照修改页面的规则，初始化页面数据
        else{
            // 装填页面数据
            setupModel()
            // 判断被保人是否存在本人
            HDApiManagerHandler.existRecognizeeSelf {[unowned self] (result:HDApiResult?) in
                guard let result = result else {
                    return // 查询错误 atk不存在
                }
                
                if result.status == .Success {
                    HDApiManagerHandler.requestCurrentRecognizeeIsSelf((self.editRecognizee?.id)!, {[unowned self] (result:HDApiResult?) in
                        guard let result = result else {
                            return
                        }
                        
                        if result.status == .Success {
                            self.relationPicker.arr = ["本人","子女"]
                        }else {
                            self.relationPicker.arr = ["子女"]
                        }
                    })
                }else{
                    self.relationPicker.arr = ["本人","子女"]
                }
            }
        }
    }
    
    /// 装填页面数据
    func setupModel() {
        guard let model = editRecognizee,
        let detail = model.partone
        else {
            return
        }

        self.recognizee.pid = model.pid
        self.recognizee.status = model.status
        self.recognizee.identify = model.identify
        self.recognizee.id = model.id
        self.recognizee.info_id = model.info_id
        self.recognizee.is_del = model.is_del
        self.recognizee.relation = model.relation
        self.detail.sex = detail.sex
        self.detail.crittype = detail.crittype
        self.detail.images = detail.images
        self.detail.born_id = detail.born_id
        self.detail.province = detail.province
        self.detail.city = detail.city
        self.detail.email = detail.email
        self.detail.critcode = detail.critcode
        self.detail.phone = detail.phone
        self.detail.subBranch = detail.subBranch
        self.detail.account_name = detail.account_name
        self.detail.accountno = detail.accountno
        self.detail.address = detail.address
        self.detail.bank = detail.bank
        self.detail.re_page = detail.re_page
        self.detail.job = detail.job
        self.detail.name = detail.name
        self.recognizee.created = model.created
        self.recognizee.parttwo = model.parttwo
        self.recognizee.uid = model.uid
        
        
        nameTF.text = detail.name
        genderLB.text = detail.sex == "1" ? "男" : "女"
        relationLB.text = model.relation == "0" ? "本人" : "子女"
        if model.relation == "2" {
            numberOfSections = 5
            // tableView.insertSections([4], with: .bottom)
            
        }else{
            numberOfSections = 4
        }
        self.tableView.reloadData()
        phoneTF.text = detail.phone
        addressTF.text = detail.address
        emailTF.text = detail.email
        accountNameTF.text = detail.account_name
        accountNumTF.text = detail.accountno
        accountNumTF2.text = detail.reaccountno
        bankNameTF.text = detail.bank
        subBankName.text = detail.subBranch
        addressBtn.setTitle(detail.province+"，"+detail.city, for: .normal)
        for dict in typePicker.arr {
            let dic = dict as! [String:String]
            if dic["typeID"] == detail.crittype {
                identifierTypeLB.text = dic["typeInfo"] ?? "请选择证件类型"
                break
            }
        }
        identifierNumTF.text = detail.critcode
        
        // 加载网络图片
        if let subStrings = model.partone?.images.split(separator: ","),
            let urls = cropImageUrls(subStrings) {
                identifierCell.manager?.addNetworkingImage(toAlbum: urls, selected: true)
        }
        
        if let subStrings = model.partone?.born_id.split(separator: ","),
            let urls = cropImageUrls(subStrings) {
            multiUploadCell.manager?.addNetworkingImage(toAlbum: urls, selected: true)
        }
    
    }
    
    /// 裁切图片地址
    func cropImageUrls(_ relativeUrls:[String.SubSequence]?) -> [String]? {
        guard let relativeUrls = relativeUrls else {
            return nil
        }
        var urls = [String]()
        for url in relativeUrls {
            
            if url.first == "."{
                if url.startIndex != Substring.Index.init(encodedOffset: 0){
                    continue
                }
                urls.append(kBaseApiv2URL + "/picc" + url.substring(from: url.index(url.startIndex, offsetBy: 2)))
            }else {
                urls.append(kBaseApiv2URL + url)
            }
        }
        return urls
    }
    
    /// 设置本人被保人默认信息
    func setDefaultOrzinfo(_ orzinfo:HDOrzinfoModel?,_ autoFill:Bool = true)  {
        nameTF.text = autoFill ? orzinfo?.name : ""
        identifierNumTF.text = autoFill ? orzinfo?.critcode : ""
        detail.crittype = autoFill ? (orzinfo?.crittype)! : ""
        phoneTF.text = autoFill ? orzinfo?.phone : ""
        if !autoFill {
            identifierTypeLB.text = "请选择证件类型"
            detail.crittype = "-1"
            return
        }
        relationLB.text = "本人"
        recognizee.relation = "0"
        for dict in typePicker.arr {
            let dic = dict as! [String:String]
            if dic["typeID"] == orzinfo?.crittype {
                identifierTypeLB.text = dic["typeInfo"] ?? "请选择证件类型"
            }
        }
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if mode == .Modify {
            identifierCell.photoView?.refreshView()
            if numberOfSections == 5{
                multiUploadCell.photoView?.refreshView()
            }
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 3 && (indexPath.row == 2||indexPath.row == 3) {
            return (identifierCell.model?.photoViewHeight)!
        }
        if indexPath.section == 4 && indexPath.row == 1 {
            return (multiUploadCell.model?.photoViewHeight)!
        }
        
        return 44.0
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        if indexPath.section == 0 {
            if indexPath.row == 1{
                genderPicker.showInView()
            }else if indexPath.row == 2{
                relationPicker.showInView()
            }
        }else if indexPath.section == 3{
            if indexPath.row == 0{
                typePicker.showInView()
            }
        }
    }
    
    @IBAction func provinceClicked(_ sender: Any) {
        addressPicker?.showInView()
    }
    
    /// 提交按钮
    @IBAction func finishAction() {
        let res = validControllers()
        if !res {
            return
        }
        SVProgressHUD.showDisableLoading("正在提交数据")
        if mode == .Add {
            addAction()
        }else{// 修改数据
            editAction()
        }
    }
    
    /// 新增被保人
    func addAction() {
        fillModel(detail)
        if (identifierCell.model?.allPhotos.count)! < 2 {
            SVProgressHUD.dismiss()
            SVProgressHUD.showError("请上传身份证正面和背面照片")
            return
        }
        // 新增流程:上传图片->完成后->发出请求
        let group = DispatchGroup.init()
        let queue = DispatchQueue.init(label: "upload")
        // 上传身份证
        if let identifierPhotos = identifierCell.model?.photos{
            for photo in identifierPhotos {
                group.enter()
                uploadImage(photo) { (url) in
                    if let url = url {
                        self.detail.images += ("," + url)
                        if let index = self.identifierCell.model?.photos?.index(of: photo){
                            self.identifierCell.model?.photos?.remove(at: index)
                        }
                    }
                    group.leave()
                }
            }
        }
        // 上传子女关系附件
        
        if recognizee.relation == "2" && multiUploadCell.model?.photos != nil {
            for photo in (multiUploadCell.model?.photos)! {
                group.enter()
                uploadImage(photo) { (url) in
                    if let url = url {
                        self.detail.born_id += (","+url)
                        if let index = self.multiUploadCell.model?.photos?.index(of: photo){
                            self.multiUploadCell.model?.photos?.remove(at: index)
                        }
                    }
                    group.leave()
                }
            }
        }
        
        /// 所有上传任务完成
        group.notify(queue: queue) {[unowned self] in
            
            HDApiManagerHandler.addRecognizee(self.recognizee, {[unowned self] (result) in
                guard let result = result else {
                    SVProgressHUD.dismiss()
                    SVProgressHUD.showError("网络开小差了，请稍后再试")
                    return // 添加出错
                }
                SVProgressHUD.dismiss()
                if result.status == .Success {
                    SVProgressHUD.showSuccess("添加成功！")
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                        self.navigationController?.popViewController(animated: true)
                    })
                }else {
                    SVProgressHUD.showError("添加失败！原因：\(result.msg ?? "")")
                }
            })
        }
    }
    
    /// 编辑被保人
    func editAction(){
        fillModel(detail)
        // 回填数据，暂时无用，为了保持数据一致
        editRecognizee?.partone?.sex = detail.sex
        editRecognizee?.relation = recognizee.relation
        editRecognizee?.partone?.province = detail.province
        editRecognizee?.partone?.city = detail.city
        editRecognizee?.partone?.crittype = detail.crittype
        
        if (identifierCell.model?.allPhotos.count)! < 2 {
            SVProgressHUD.dismiss()
            SVProgressHUD.showError("请上传身份证正面和背面照片")
            return
        }
        
        let group = DispatchGroup.init()
        let queue = DispatchQueue.init(label: "upload")
        // 上传身份证
        
        if let identifierPhotos = identifierCell.model?.photos {
            for photo in identifierPhotos {
                group.enter()
                uploadImage(photo) {[unowned self] (url) in
                    if let url = url {
                        
                        self.editRecognizee?.partone?.images += ("," + url)
                        if let index = self.identifierCell.model?.photos?.index(of: photo){
                            self.identifierCell.model?.photos?.remove(at: index)
                        }
                    }
                    group.leave()
                }
            }
        }
        // 上传子女关系附件
        
        if let relationPhotos = multiUploadCell.model?.photos {
            if recognizee.relation == "2" {
                for photo in relationPhotos {
                    group.enter()
                    uploadImage(photo) {[unowned self] (url) in
                        if let url = url {
                            self.editRecognizee?.partone?.born_id += (","+url)
                            if let index = self.multiUploadCell.model?.photos?.index(of: photo){
                                self.multiUploadCell.model?.photos?.remove(at: index)
                            }
                            
                        }
                        group.leave()
                    }
                }
            }
        }
        
        /// 所有上传任务完成
        group.notify(queue: queue) {[unowned self] in
            if let images = self.editRecognizee?.partone?.images {
                self.detail.images = images
            }
            
            if let born_id = self.editRecognizee?.partone?.born_id {
                self.detail.born_id = born_id
            }
            
            // 修改被保人信息
            self.recognizee.info_id = (self.editRecognizee?.id)!

            HDApiManagerHandler.addRecognizee(self.recognizee, {[unowned self] (result) in
                guard let result = result else {
                    SVProgressHUD.dismiss()
                    SVProgressHUD.showError("网络开小差了，请稍后再试")
                    return // 添加出错
                }
                SVProgressHUD.dismiss()
                if result.status == .Success {
                    SVProgressHUD.showSuccess("修改成功！")
                    DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1, execute: {
                        self.navigationController?.popViewController(animated: true)
                    })
                }else {
                    SVProgressHUD.showError("修改失败！原因：\(result.msg ?? "")")
                }
            })
        }
    }
    
    /// 页面控件数据 向 模型填充
    func fillModel(_ detail:HDRecognizeeDetailModel) {
        detail.name = nameTF.text!
        detail.phone = phoneTF.text!
        detail.address = addressTF.text!
        detail.email = emailTF.text!
        detail.account_name = accountNameTF.text!
        detail.accountno = accountNumTF.text!
        detail.reaccountno = accountNumTF2.text!
        detail.reaccountno = accountNumTF2.text!
        detail.bank = bankNameTF.text!
        detail.subBranch = subBankName.text!
        detail.critcode = identifierNumTF.text!
    }
    
    /// 校验页面控件数据
    func validControllers() -> Bool {
        if nameTF.text == nil || nameTF.text == "" {
            progressAlert.pleaseEnterName()
            return false
        }
        if phoneTF.text == nil || phoneTF.text == "" {
            progressAlert.pleaseEnterPhoneNumber()
            return false
        }
        
        if !(recognizee.relation == "0" && phoneTF.text! == self.orzinfo?.phone) {
            if !PredicateHelper.validateTelNumber(telnum: phoneTF.text!)  {
                phoneTF.becomeFirstResponder()
                SVProgressHUD.showError("请输入有效的电话号码")
                return false
            }
        }
        
        if addressTF.text == nil || addressTF.text == "" {
            SVProgressHUD.showError("请输入"+addressTF.placeholder!)
            return false
        }
        if emailTF.text == nil || emailTF.text == "" {
            SVProgressHUD.showError("请输入"+emailTF.placeholder!)
            return false
        }
        if !PredicateHelper.validateEmail(email: emailTF.text!) {
            emailTF.becomeFirstResponder()
            SVProgressHUD.showError("请输入有效的电子邮箱地址")
            return false
        }
        if accountNameTF.text == nil || accountNameTF.text == "" {
            SVProgressHUD.showError("请输入"+accountNameTF.placeholder!)
            return false
        }
        if accountNumTF.text == nil || accountNumTF.text == "" {
            SVProgressHUD.showError("请输入"+accountNumTF.placeholder!)
            return false
        }
        if accountNumTF2.text == nil || accountNumTF2.text == "" {
            SVProgressHUD.showError("请输入"+accountNumTF2.placeholder!)
            return false
        }
        if accountNumTF.text != accountNumTF2.text {
            SVProgressHUD.showError("请确认两次输入的银行账号相同！")
            return false
        }
        if !PredicateHelper.validateBankCard(bankCard: accountNumTF.text!){
            accountNumTF.becomeFirstResponder()
            SVProgressHUD.showError("请输入有效的银行卡号")
            return false
        }
        if bankNameTF.text == nil || bankNameTF.text == "" {
            SVProgressHUD.showError("请输入"+bankNameTF.placeholder!)
            return false
        }
        if subBankName.text == nil || subBankName.text == "" {
            SVProgressHUD.showError("请输入"+subBankName.placeholder!)
            return false
        }
        if identifierTypeLB.text == "请选择证件类型：" {
            SVProgressHUD.showError("请选择证件类型")
            return false
        }
        if identifierNumTF.text == nil || identifierNumTF.text == "" {
            SVProgressHUD.showError("请输入"+identifierNumTF.placeholder!)
            return false
        }
        if addressBtn.title(for: .normal) == "省份，城市" {
            SVProgressHUD.showError("请选择开户行所在省份，城市")
            return false
        }
        if genderLB.text == "性别" {
            SVProgressHUD.showError("请选择被保人性别")
            return false
        }
        if relationLB.text == "关系" {
            SVProgressHUD.showError("请选择被保人与主保人关系")
            return false
        }
        return true
    }
    
    /// 上传图片
    func uploadImage(_ image:UIImage,_ completionHandler:@escaping (_ url:String?)->()) {
        HDApiManagerHandler.uploadBase64Image(kBaseApiv2URL+"/apiv1_imguploads/index", "img", image) { (result) in
            if result?.status == .Success {
                let model = HDUploadImageResponse.yy_model(withJSON: result?.data ?? "")
                completionHandler(model?.imgurl)
            }else{
                completionHandler(nil)
            }
        }
    }
    
    override func numberOfSections(in tableView: UITableView) -> Int {
        return numberOfSections
    }
}

extension HDRecognizeeEditVC : AddressDelegate{
    func complete(_ addressView: UIView!, str: String!) { }
    
    func reback(_ addressView: UIView!, pro: String!, city: String!, area: String!) {
        if pro == nil || city == nil || pro == "" || city == ""{
            addressBtn.setTitle("省份，城市", for: .normal)
            return
        }
        
        detail.province = pro
        detail.city = city
        addressBtn.setTitle(pro+"，"+city, for: .normal)
    }
    
    func selectId(_ addressView: UIView!, pro proId: NSNumber!, city cityId: NSNumber!, area areaId: NSNumber!) { }
}

extension HDRecognizeeEditVC : SinglePickerViewDelegate{
    
    func complete(_ pickerView: UIView!, tempStr str: String!, idStr idstr: String!) {
        if pickerView == self.genderPicker {
            genderLB.text = str
            detail.sex = (str == "男" ? "1" : "2")
        }else if pickerView == self.relationPicker {
            relationLB.text = str
            recognizee.relation = (str == "本人" ? "0" : "2")
            
            if str == "子女" {
                numberOfSections = 5
                if tableView.numberOfSections < numberOfSections {
                    // tableView.insertSections([4], with: .bottom)
                    self.tableView.reloadData()
                }
                self.setDefaultOrzinfo(self.orzinfo, false)
            }else{
                numberOfSections = 4
                if tableView.numberOfSections > numberOfSections {
                    // tableView.deleteSections([4], with: .bottom)
                    self.tableView.reloadData()
                }
            }
        }else if pickerView == self.typePicker {
            identifierTypeLB.text = str
            detail.crittype = idstr
        }
    }
}
